package render
{
	import render.tree.AttributeNode;
	import render.tree.CategoryNode;
	import render.tree.InstanceNode;
	import render.tree.StructureDescriptor;
	import render.tree.TreeStructureRender;
	
	public class TreeRender extends TreeStructureRender implements SemanticDataRender
	{
		private static const SubCategoryTag:String = "<http://www.w3.org/2000/01/rdf-schema#subClassOf>";
		private var fetcherImpl:Function;
		private var currentFetchHandler:Function;
		private var currentURI:String;
		
		public function TreeRender()
		{
		}
		private function initFromNt(nt:String):CategoryNode
		{
			if(nt == null)
				return null;
				
			var ntData:NTData = new NTData(nt);
			var root:CategoryNode = new CategoryNode(this,Triple(ntData.triples[0]).subject,null);
			for each( var triple:Triple in ntData.triples ){
				if(triple.predicateType() == Triple.REL){
					root.pushItem(new InstanceNode(this,triple.object,triple.predicate));
				}
				else if(triple.predicateType() == Triple.ATTR){
					root.pushItem(new AttributeNode(this, triple.object,triple.predicate));
				}
			}
			root.sort();
			root.solid();
			
			return root;
		}
		public function set dataSource(nt:String):void
		{
			trace(" tree render got " + nt );
			dataProvider = initFromNt(nt);			
		}
		
		override public function set rootURI(uri:String):void
		{
			super.rootURI = uri;
		}
		
		override public function set fetcherFunction(func:Function):void
		{
			fetcherImpl = func;			
			super.fetcherFunction = fetcher
		}
		public function fetcher(tfetchHandler:Function, uri:String,index:int,pageSize:int):void
		{
			currentFetchHandler = tfetchHandler;
			currentURI = uri;
			fetcherImpl.call(this,fetcherHandler,uri,index,pageSize);
		}
		
		private function fetcherHandler(triples:Array):void
		{
			var result:Array = new Array();
			var tc:String = currentURI;
			if(tc.charAt(0) != "<")
				tc = "<" + tc + ">";
			for each( var triple:Triple in triples ){
				if(triple.subject == tc ){
					var nodeType:String;
					var uriVar:String;
					var edgeName:String;
					
					if(triple.predicateType() == Triple.REL)
						nodeType = StructureDescriptor.NODE_TYPE_INSTANCE;
					else
						nodeType = StructureDescriptor.NODE_TYPE_ATTRIBUTE;
						
					uriVar = triple.object;
					
					edgeName = triple.predicate;
					
					result.push({nodeType:nodeType,uri:uriVar,edgeName:edgeName});
				}
				else if(triple.object == tc){
					if( triple.predicate == SubCategoryTag)
						result.push({nodeType:StructureDescriptor.NODE_TYPE_CATEGORY,uri:triple.subject,edgeName:"subClassOf"});
					else
						result.push({nodeType:StructureDescriptor.NODE_TYPE_INSTANCE,uri:triple.subject,edgeName:triple.predicate});
				}
			}
			currentFetchHandler.call(this,result);
		}
		
	}
}